﻿using AutoMapper;
using B.S.Packaged.ErrorCode;
using B.S.Packaged.Infra;
using B.S.Packaged.WebAPI.Read.Application.Command.MaterialPreparation;
using B.S.Packaged.WebAPI.Read.Dtos;
using MediatR;

namespace B.S.Packaged.WebAPI.Read.Application.CommandHander.MaterialPreparation
{
    public class GetMaterialPreparationHander : IRequestHandler<GetMaterialPreparationCommand, APIPaging<List<MaterialPreparationDto>>>
    {
        private readonly IMapper mapper;
        private readonly DapperContext context;

        public GetMaterialPreparationHander(IMapper mapper, DapperContext context)
        {
            this.mapper = mapper;
            this.context = context;
        }

        /// <summary>
        /// 显示物料备料信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIPaging<List<MaterialPreparationDto>>> Handle(GetMaterialPreparationCommand request, CancellationToken cancellationToken)
        {
            APIPaging<List<MaterialPreparationDto>> paging = new APIPaging<List<MaterialPreparationDto>>();
            paging.code = APIResultCode.success;
            paging.msg = APIResultCode.success.ToString();

            try
            {
                // 计算偏移量
                int offset = (request.TotalIndex - 1) * request.TotalPage;
                // 构建 MySQL 分页查询语句
                var listQuery = $"SELECT * FROM MaterialPreparation ORDER BY ItemNumber ASC LIMIT {offset}, {request.TotalPage};";
                var totalCountQuery = "SELECT COUNT(*) FROM MaterialPreparation";

                // 查询总记录数
                paging.TotalCount = await context.QuerySingleAsync<int>(totalCountQuery);

                // 计算总页数
                paging.TotalPage = (int)Math.Ceiling((double)paging.TotalCount / request.TotalPage);

                // 执行分页查询
                var result = await context.QueryAsync<MaterialPreparationDto>(listQuery);
                paging.data = result.ToList();
            }
            catch (Exception ex)
            {
                // 处理异常
                paging.code = APIResultCode.failed;
                paging.msg = $"查询失败: {ex.Message}";
                paging.data = new List<MaterialPreparationDto>();
            }

            return paging;
        }
    }
}